import { defineStore } from 'pinia'
import { ref } from 'vue'
import router from '@/router/index.js'
import staticRoutes from '@/router/staticRoutes'
import request from '@/api/request'
import filterRoutesByPermission from '@/utils/findAllowedRoutes'

export const userInfoStore = defineStore('userInfo', () => {
  const tokens = ref(localStorage.getItem('token') || '')
  const userAuth = ref([])
  const userRoutes = ref([])
  // 控制页面刷新
  const sign = ref(false)

  // 获取token
  const getTokens = async () => {
    const result = await request.get('/api/token')
    tokens.value = result.token

    if (!localStorage.getItem('token') && tokens.value) {
      localStorage.setItem('token', tokens.value)
    }
  }
  // 清除token
  const clearTokens = () => {
    localStorage.removeItem('token')
    // 页面跳转
    router.push('/login')
    // 刷新页面 清除用户页面缓存
    window.location.reload(true)
  }
  // 获取用户权限
  const setUserAllowedRoutes = async () => {
    const result = await request.get('/api/auth1')
    userAuth.value = result.roles
    // 代表用户信息成功获取
    sign.value = true
    const userRoles = filterRoutesByPermission(staticRoutes, result.roles)
    // 添加动态路由
    userRoutes.value = userRoles
    userRoles.forEach(route => {
      router.addRoute(route)
    })
  }
  // 清除用户页面

  return {
    tokens,
    userAuth,
    getTokens,
    setUserAllowedRoutes,
    clearTokens,
    sign
  }
})
